﻿using System;
using System.Globalization;
using System.Web.Mvc;
using BookShop.BLL;
using BookShop.DTO;
using BookShop.Library.Common;
using BookShop.Library.Constant;
using PagedList;

namespace BookShop.Admin.Controllers
{
    public class DiscountController : Controller
    {
        public ActionResult Add()
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.DiscountWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(long bookId, int percentage, string startDate, string endDate)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.DiscountWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var discount = new Discount { BookId = bookId, Percentage = percentage };
            DateTime newStartDate;
            var isValidStartDate = DateTime.TryParse(startDate, CultureInfo.CreateSpecificCulture("vi-VN"),
                DateTimeStyles.None, out newStartDate);
            DateTime newEndDate;
            var isValidEndDate = DateTime.TryParse(endDate, CultureInfo.CreateSpecificCulture("vi-VN"),
                DateTimeStyles.None, out newEndDate);
            if (isValidStartDate)
            {
                discount.StartDate = newStartDate;
            }
            if (isValidEndDate)
            {
                discount.EndDate = newEndDate;
            }
            var addResult = DiscountService.Add(discount);
            if (addResult != null)
            {
                return RedirectToAction("Detail", new { discountId = addResult.Id });
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.ErrorOccurs;
            ViewBag.AddBookId = bookId;
            ViewBag.AddPercentage = percentage;
            ViewBag.AddStartDate = startDate ?? string.Empty;
            ViewBag.AddEndDate = endDate ?? string.Empty;
            return View();
        }

        public ActionResult Delete(long discountId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.DiscountWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var deleteResult = DiscountService.Delete(discountId);
            if (!deleteResult)
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.ErrorOccurs;
            }
            return RedirectToAction("List");
        }

        public ActionResult Detail(long discountId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.DiscountRead))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var discount = DiscountService.GetById(discountId);
            if (discount != null)
            {
                discount.BookTitle = (BookService.GetById(discount.BookId) ?? new Book()).Title;
                return View(discount);
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.NotFoundObject;
            return RedirectToAction("List");
        }

        public ActionResult Edit(long discountId)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.DiscountWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var discount = DiscountService.GetById(discountId);
            if (discount != null)
            {
                return View(discount);
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.NotFoundObject;
            return RedirectToAction("List");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(long discountId, long bookId, int percentage, string startDate, string endDate)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.DiscountWrite))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("List");
            }
            var discount = DiscountService.GetById(discountId);
            if (discount == null)
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.NotFoundObject;
                return RedirectToAction("List");
            }
            discount.BookId = bookId;
            discount.Percentage = percentage;
            DateTime newStartDate;
            var isValidStartDate = DateTime.TryParse(startDate, CultureInfo.CreateSpecificCulture("vi-VN"),
                DateTimeStyles.None, out newStartDate);
            DateTime newEndDate;
            var isValidEndDate = DateTime.TryParse(endDate, CultureInfo.CreateSpecificCulture("vi-VN"),
                DateTimeStyles.None, out newEndDate);
            if (isValidStartDate)
            {
                discount.StartDate = newStartDate;
            }
            if (isValidEndDate)
            {
                discount.EndDate = newEndDate;
            }
            var editResult = DiscountService.Update(discount);
            if (editResult != null)
            {
                return RedirectToAction("Detail", new { discountId });
            }
            TempData[AlertMessage.TempDataKey] = AlertMessage.ErrorOccurs;
            return View(discount);
        }

        [ValidateInput(false)]
        public ActionResult List(long? discountId, long? bookId, string fromStartDate, string toStartDate,
            string fromEndDate, string toEndDate, int page = 1, int pageSize = 15)
        {
            var mod = (Moderator)Session[SessionKey.Moderator];
            if (mod == null)
            {
                return RedirectToAction("Login", "Home");
            }
            if (!CommonFunction.CheckModeratorRole(mod, ModeratorRole.DiscountRead))
            {
                TempData[AlertMessage.TempDataKey] = AlertMessage.UnauthorizedAction;
                return RedirectToAction("Index", "Home");
            }
            int totalRow;
            var model = DiscountService.Search(discountId, bookId, fromStartDate, toStartDate, fromEndDate, toEndDate,
                page, pageSize, out totalRow);
            ViewBag.SearchId = discountId.ToString();
            ViewBag.SearchBookId = bookId.ToString();
            ViewBag.SearchFromStartDate = fromStartDate ?? string.Empty;
            ViewBag.SearchToStartDate = toStartDate ?? string.Empty;
            ViewBag.SearchFromEndDate = fromEndDate ?? string.Empty;
            ViewBag.SearchToEndDate = toEndDate ?? string.Empty;
            ViewBag.PageList = new StaticPagedList<Discount>(model, page, pageSize, totalRow);
            ViewBag.RecordsCount = "Tổng số bản ghi: " + totalRow;
            return View(model);
        }

        public JsonResult GetAllBook()
        {
            return Json(BookService.GetAll());
        }
    }
}
